<?php

namespace common\models\db;

use Yii;
use common\components\wtools\tools\ArrayHelper;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use common\components\wsoftdelete\SoftDeleteTrait;
use common\components\wsoftdelete\SoftDeleteBehavior;

/**
 * This is the model class for table "{{%building_orders}}".
 *
 * @author
 * @property BaseAreas $county
 * @property BaseAreas $city
 * @property BaseAreas $province
 * @property Adminers $createdByAdmin
 * @property Adminers $updatedByAdmin
 */
class BuildingOrders extends \common\models\db\tables\BuildingOrders
{
    const SCENARIO_TEST = 'test';

    use SoftDeleteTrait;

    public static function getDeletedAtAttribute()
    {
        return "deleted_at";
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors = ArrayHelper::merge($behaviors, [
            'timestamp' => [
                'class' => TimestampBehavior::class,
            ],
            'blameable' => [
                'class' => BlameableBehavior::class,
                'createdByAttribute' => false,
                'updatedByAttribute' => false,
            ],
            'soft-delete' => [
                'class' => SoftDeleteBehavior::class,
                'deletedAtAttribute' => static::getDeletedAtAttribute(),
            ],
        ]);
        return $behaviors;
    }

    public function attributeLabels()
    {
        $attributeLabels = parent::attributeLabels();
        $attributeLabels = ArrayHelper::merge($attributeLabels, [
            'county_id' => "乡镇街道",
            'address' => "详细地址",
        ]);
        return $attributeLabels;
    }

    public function rules()
    {
        $rules = parent::rules();
        foreach ($rules as $k => $v) {
            if ($v[1] == 'required'){
                $rules[$k][0] = array_diff($rules[$k][0], ['created_at', 'updated_at']);
            }
        }
        $rules = ArrayHelper::merge($rules, [
//            [[], 'required', 'on' => self::SCENARIO_TEST],
        ]);
        return $rules;
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios = ArrayHelper::merge($scenarios, [
            self::SCENARIO_TEST => [],
        ]);
        return $scenarios;
    }

    const STATUS_1 = 1;
    const STATUS_2 = 2;
    const STATUS_3 = 3;
    const STATUS_4 = 4;
    const STATUS_200 = 200;

    public static function getStatusDatas()
    {
        return [
            self::STATUS_1 => ['已提交'],
            self::STATUS_2 => ['跟进中'],
            self::STATUS_3 => ['测量中'],
            self::STATUS_4 => ['施工中'],
            self::STATUS_200 => ['已完成'],
        ];
    }

    public static function getStatusDesc()
    {
        $arr = [];
        foreach (static::getStatusDatas() as $k => $v) {
            $arr[$k] = $v[0];
        }
        return $arr;
    }

    public static function getOrSetLastUpdatedAt($updatedAt = 0)
    {
        if ($updatedAt > 0) {
            Yii::$app->cache->delete("db-BuildingOrders-getOrSetLastUpdatedAt");
        }
        return Yii::$app->cache->getOrSet("db-BuildingOrders-getOrSetLastUpdatedAt", function () use ($updatedAt) {
            if ($updatedAt > 0) {
                return $updatedAt;
            }
            $lastModel = static::findWithTrashed()->orderBy(['updated_at' => SORT_DESC])->one();
            return $lastModel ? $lastModel->updated_at : 0;
        });
    }

    /**
     * @return false|mixed|BuildingOrders[]
     */
    public static function getAllWithCache()
    {
        return Yii::$app->cache->getOrSet("db-BuildingOrders-getAllWithCache", function () {
            return static::find()->all();
        }, null);
    }

    /**
     * @param $id
     * @return false|BuildingOrders|mixed
     */
    public static function getByIdWithCache($id)
    {
        return Yii::$app->cache->getOrSet("db-BuildingOrders-getByIdWithCache/{$id}", function () use ($id) {
            return static::findOne($id);
        }, null);
    }

    public function deleteCaches()
    {
        Yii::$app->cache->delete("db-BuildingOrders-getAllWithCache");
        Yii::$app->cache->delete("db-BuildingOrders-getByIdWithCache/{$this->id}");
        static::getOrSetLastUpdatedAt(time());
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        $this->deleteCaches();
    }

    public function afterRefresh()
    {
        parent::afterRefresh();
        $this->deleteCaches();
    }

    public function afterDelete()
    {
        parent::afterDelete();
        $this->deleteCaches();
    }

    public function afterRestore()
    {
        $this->deleteCaches();
    }

    # relations

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCounty()
    {
        return $this->hasOne(BaseAreas::className(), ['id' => 'county_id'])
            ->andWhere(['level' => 3]);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCity()
    {
        return $this->hasOne(BaseAreas::className(), ['id' => 'city_id'])
            ->andWhere(['level' => 2]);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProvince()
    {
        return $this->hasOne(BaseAreas::className(), ['id' => 'province_id'])
            ->andWhere(['level' => 1]);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCreatedByAdmin()
    {
        return $this->hasOne(Adminers::className(), ['id' => 'created_by_admin']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUpdatedByAdmin()
    {
        return $this->hasOne(Adminers::className(), ['id' => 'updated_by_admin']);
    }

    # static funs

    public function test()
    {
        $test = self::instance();
        $test->setScenario(self::SCENARIO_TEST);
        $test->save();
        var_dump($test->toArray());
    }

    # funs
}
